package TCPConnector

import (
	"fmt"
	"log"
	"net"
	"strings"

	"gitee.com/csingo/cHelper"
)

func Server(port string) {
	listener, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
	if err != nil {
		log.Panic(err)
	}

	for {
		var conn net.Conn
		conn, err = listener.Accept()
		if err != nil {
			log.Panic(err)
		}

		go receive(conn)
	}
}

func receive(conn net.Conn) {
	defer func() {
		if r := recover(); r != nil {
			log.Println(r)
		}
	}()
	for {
		buffer := make([]byte, buf)
		_, err := conn.Read(buffer)
		if err != nil {
			panic(err)
		}

		var body []byte
		for _, item := range buffer {
			if item != 0 {
				body = append(body, item)
			}
		}

		verify, err := cHelper.PasswordHash(strings.ToUpper(string(body)))
		if err != nil {
			panic(err)
		}

		var response []byte
		for _, item := range []byte(verify) {
			response = append(response, item+offset)
		}

		_, err = conn.Write(response)
		if err != nil {
			panic(err)
		}

		log.Println("Client =>", conn.RemoteAddr())
	}
}
